<template>
  <el-card style="height: 70px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户姓名">
        <el-input placeholder="请输入用户姓名" v-model="username"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getUserList()">搜索</el-button>
        <el-button @click="reflush">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <el-card style="margin: 20px 0px">
    <el-button type="primary" @click="addUser">添加用户</el-button>
    <el-button
      type="primary"
      :disabled="selectList.length < 1"
      @click="removes"
    >
      批量删除
    </el-button>
    <el-table
      border
      style="margin: 20px 0px"
      :data="userList"
      @selection-change="changeSelect"
    >
      <el-table-column type="selection" width="50px"></el-table-column>
      <el-table-column
        label="#"
        align="center"
        type="index"
        width="80px"
      ></el-table-column>
      <el-table-column
        label="id"
        align="center"
        width="80px"
        prop="id"
      ></el-table-column>
      <el-table-column
        label="用户名字"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="270px">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="distributionRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`您确定删除${row.username}吗？`"
            @confirm="remove(row.id)"
            width="200px"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :background="true"
      layout=" prev, pager, next, jumper,->,sizes,total,"
      :total="total"
      @size-change="handel"
      @current-change="getUserList"
    />
  </el-card>

  <el-drawer v-model="drawer">
    <template #header>
      <h4>{{ user.id ? '修改用户' : '添加用户' }}</h4>
    </template>
    <template #default>
      <el-form label-width="120px" ref="formRef" :rules="rules" :model="user">
        <el-form-item label="用户名字" prop="username">
          <el-input
            placeholder="请输入用户名字"
            v-model="user.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input placeholder="请输入用户昵称" v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item v-if="!user.id" label="用户密码" prop="password">
          <el-input
            placeholder="请输入用户密码"
            v-model="user.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" @click="saveOrUpdate">提交</el-button>
          <el-button @click="drawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>

  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色</h4>
    </template>
    <template #default>
      <el-form label-width="120px">
        <el-form-item label="用户名字">
          <el-input disabled="true" v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
            v-model="assignRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRolesList"
              :key="index"
              :label="role"
            >
              {{ role?.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="updateRole">提交</el-button>
          <el-button @click="drawer1 = false">取消</el-button>
        </el-form-item>
      </el-form>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqUserList,
  reqSave,
  reqUpdate,
  reqToAssign,
  reqDoAssignRole,
  reqRemove,
  reqBatchRemove,
} from '@/api/auth/user'
import { ElMessage } from 'element-plus'
let checkAll = ref(false)
let isIndeterminate = ref(false)
let username = ref('')
let page = ref(1)
let pageSize = ref(5)
let total = ref(20)
let userList = ref([])
let drawer = ref(false)
let formRef = ref()
let drawer1 = ref(false)
let allRolesList = ref([])
let assignRoles = ref([])
let selectList = ref([])
let user = reactive({
  id: 0,
  username: '',
  name: '',
  password: '',
})
onMounted(() => {
  getUserList()
})
//勾选回调
// @ts-ignore
const changeSelect = (selection) => {
  selectList.value = selection
}

//batchRemove
const removes = async () => {
  let data = {
    data: selectList.value.map((item) => item.id),
  }
  let res = await reqBatchRemove(data)
  // @ts-ignore
  if (res?.code == 200) {
    ElMessage.success('批量删除成功')
  } else {
    ElMessage.error('批量删除失败')
  }
  getUserList()
}
//updateRole
const updateRole = async () => {
  let data = {
    userId: user.id,
    // @ts-ignore
    roleIdList: assignRoles.value.map((item) => item?.id),
  }
  let res = await reqDoAssignRole(data)
  // @ts-ignore
  if (res?.code == 200) {
    ElMessage.success('分配角色成功')
  } else {
    ElMessage.error('分配角色失败')
  }
  drawer1.value = false
  getUserList(page.value)
}
//handleCheckedCitiesChange
// @ts-ignore
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRolesList.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRolesList.value.length
}
//handleCheckAllChange
// @ts-ignore
const handleCheckAllChange = (val) => {
  assignRoles.value = val ? allRolesList.value : []
  isIndeterminate.value = false
}
//userList
const getUserList = async (page1 = 1) => {
  page.value = page1
  let res = await reqUserList(page.value, pageSize.value, username.value)
  if (res.code == 200) {
    userList.value = res.data.records
    total.value = res.data.total
  }
}
//handel
const handel = () => {
  getUserList()
}
//reflush
const reflush = () => {
  username.value = ''
  getUserList()
}
//addUser
const addUser = () => {
  drawer.value = true
  Object.assign(user, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
//updateUser
const updateUser = (row) => {
  Object.assign(user, row)
  drawer.value = true
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
//saveOrUpdate
const saveOrUpdate = async () => {
  await formRef.value.validate()
  if (user.id) {
    let update = { username: user.username, name: user.name, id: user.id }
    let res = await reqUpdate(update)
    if (res?.code == 200) {
      ElMessage.success('修改成功')
      window.location.reload()
    } else {
      ElMessage.error(res?.message)
    }
  } else {
    let res = await reqSave(user)
    if (res?.code == 200) {
      ElMessage.success('添加成功')
    } else {
      ElMessage.error(res?.message)
    }
    getUserList()
  }
  drawer.value = false
}
const validUsername = (rule, value, callback) => {
  if (value.trim().length < 5) {
    callback(new Error('用户名字必须大于4位'))
  }
  callback()
}
const validName = (rule, value, callback) => {
  if (value.trim().length < 5) {
    callback(new Error('用户名称必须大于4位'))
  }
  callback()
}
const validPassword = (rule, value, callback) => {
  if (value.trim().length < 6) {
    callback(new Error('用户密码必须大于5位'))
  }
  callback()
}
//rules
let rules = reactive({
  username: [{ required: true, trigger: 'blur', validator: validUsername }],
  name: [{ required: true, trigger: 'blur', validator: validName }],
  password: [{ required: true, trigger: 'blur', validator: validPassword }],
})
//distributionRole
const distributionRole = async (row) => {
  Object.assign(user, row)
  drawer1.value = true
  let res = await reqToAssign(row.id)
  allRolesList.value = res.data.allRolesList
  assignRoles.value = res.data.assignRoles
}
//remove
const remove = async (userId) => {
  let res = await reqRemove(userId)
  if (res?.code == 200) {
    ElMessage.success('删除成功')
    getUserList(userList.value.length > 1 ? page.value : page.value - 1)
  } else {
    ElMessage.error('删除失败')
  }
}
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
}
</style>
